/**
 * 
 */
package com.cn.daifaming.demoservice.common.utils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * @author Administrator
 *
 */
public class EmailSendUtil
{
	private static JavaMailSenderImpl mailSender = createMailSender();
	/**
	 * 邮件发送器
	 *
	 * @return 配置好的工具
	 */
	private static JavaMailSenderImpl createMailSender()
	{
		JavaMailSenderImpl sender = new JavaMailSenderImpl();;
		sender.setHost(CustomizedPropertyConfigurer.getContextProperty("host"));
		sender.setPort(Integer.valueOf(
				CustomizedPropertyConfigurer.getContextProperty("port")));
		sender.setUsername(
				CustomizedPropertyConfigurer.getContextProperty("username"));
		sender.setPassword(
				CustomizedPropertyConfigurer.getContextProperty("passwd"));
		sender.setDefaultEncoding("Utf-8");
		Properties p = new Properties();
		p.setProperty("mail.smtp.timeout", "25000");
		p.setProperty("mail.smtp.auth", "false");
		sender.setJavaMailProperties(p);
		return sender;
	}

	/**
	 * 发送邮件
	 *
	 * @param to
	 *            接受人
	 * @param subject
	 *            主题
	 * @param template
	 *            发送模板
	 * @param map
	 *            变量
	 * @throws MessagingException
	 *             异常
	 * @throws UnsupportedEncodingException
	 *             异常
	 */
	public static void sendHtmlMail(String to, String subject, String template, Map<String,String> map)
	{
		for (String s : map.keySet())
		{
			template = template.replaceAll(
					"\\$\\{".concat(s.toString()).concat("\\}"),
					map.get(s));
		}

		MimeMessage mimeMessage = mailSender.createMimeMessage();
		// 设置utf-8或GBK编码，否则邮件会有乱码

		try
		{
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,
					true, "UTF-8");
			messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

			messageHelper.setFrom(CustomizedPropertyConfigurer
					.getContextProperty("emailfrom"), "系统邮件");
			messageHelper.setTo(to);
			messageHelper.setSubject(subject);
			messageHelper.setText(template, true);
		} catch (MessagingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		mailSender.send(mimeMessage);
	}
}
